﻿Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Configuration
Imports BusinessLayer
Imports CommonLayer

Public Class frmLogIn

#Region "Declare"

    Public Const mscConnectionName As String = "MyConnection"

#End Region

#Region "Property"

    Public ReadOnly Property UserName() As String
        Get
            Return txtUserName.Text
        End Get
    End Property

#End Region


#Region "Overridable"

#End Region

#Region "Sub/Function"

    Private Sub SaveLogInInfoToConfig()
        Dim oBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
        Dim oConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Dim oSession As ConnectionStringsSection = oConfig.ConnectionStrings

        Dim stringConnection As String = BuildConnectionString(cboSQLInstance.Text, cboDatabase.Text, True, "", "")
        Dim oConnSetting As ConnectionStringSettings = Nothing

        If Not IsDBNull(oSession.ConnectionStrings(mscConnectionName)) Then
            oConnSetting = oSession.ConnectionStrings(mscConnectionName)
            oConnSetting.ConnectionString = stringConnection
        Else
            oConnSetting = New ConnectionStringSettings(mscConnectionName, stringConnection)
            oConnSetting.ProviderName = "System.Data.SqlClient"
            oSession.ConnectionStrings.Add(oConnSetting)
        End If

        oConfig.Save()
        ConfigurationManager.RefreshSection("connectionStrings")
    End Sub

    Public Function BuildConnectionString(ByVal strSqlServer As String, ByVal sDatabase As String, _
                                          ByVal IsWindowsAuthentication As Boolean, ByVal sUser As String, _
                                          ByVal sPass As String) As String

        Dim oBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
        oBuilder.DataSource = strSqlServer
        oBuilder.InitialCatalog = sDatabase
        oBuilder.IntegratedSecurity = IsWindowsAuthentication
        If Not IsWindowsAuthentication Then
            oBuilder.UserID = sUser
            oBuilder.Password = sPass
        End If
        oBuilder.MultipleActiveResultSets = True
        oBuilder.ConnectTimeout = 15
        Return oBuilder.ConnectionString
    End Function

#End Region

#Region "Event"

    Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
        Try
            If txtUserName.Text.Trim = "" Then
                CommonFunction.ShowExclamation("Tên đăng nhập không được bỏ trống!")
                txtUserName.Focus()
                Return
            End If

            Dim stringConnection As String = BuildConnectionString(cboSQLInstance.Text, cboDatabase.Text, True, "", "")
            Dim eLogIn As LogInStatus = BLSecurity.CheckLogIn(stringConnection, txtUserName.Text.Trim, _
                                                              CommonFunction.EncryptMD5(txtPassword.Text))

            If Not CommonFunction.mscBuildApplication Then
                eLogIn = LogInStatus.Success
            End If

            Select Case eLogIn
                Case LogInStatus.LogInInfoWrong
                    CommonFunction.ShowExclamation( _
                        "Thông tin đăng nhập không đúng. Vui lòng nhập lại thông tin đăng nhập!")
                    txtUserName.Focus()
                    Return
                Case LogInStatus.Success
                    SaveSetting(Application.ProductName, "ServerName", "ServerName", cboSQLInstance.Text)
                    SaveSetting(Application.ProductName, "DatabaseName", "DatabaseName", cboDatabase.Text)
                    SaveSetting(Application.ProductName, "CurrentUser", "CurrentUser", txtUserName.Text.Trim)
                    SaveLogInInfoToConfig()
                    Me.DialogResult = DialogResult.OK
                Case LogInStatus.UserLock
                    CommonFunction.ShowExclamation( _
                        "Người dùng: " & txtUserName.Text.Trim & _
                        " đang bị khóa. Vui lòng liên hệ với Admin để trợ giúp!")
                    txtUserName.Focus()
                    Return
            End Select


        Catch ex As Exception
            CommonFunction.ShowExclamation(ex.ToString)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
        Try
            Me.DialogResult = DialogResult.Cancel
        Catch ex As Exception
            CommonFunction.ShowExclamation(ex.ToString)
        End Try
    End Sub

    Private Sub cboSQLInstance_QueryPopUp(ByVal sender As Object, ByVal e As CancelEventArgs) _
        Handles cboSQLInstance.BeforeDropDown
        Try
            If cboSQLInstance.Items.Count = 0 Then
                Cursor = Cursors.WaitCursor
                Dim dtServerList As New DataTable
                Dim oDM As New DatabaseManagement.BL.DatabaseManagement
                dtServerList = oDM.ListServer
                With cboSQLInstance
                    .Items.Clear()
                    For Each dr As DataRow In dtServerList.Rows
                        .Items.Add(dr(0))
                    Next
                End With
            End If
        Catch ex As Exception

            CommonFunction.ShowExclamation(ex.ToString)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub cbodatabase_QueryPopUp(ByVal sender As Object, ByVal e As CancelEventArgs) _
        Handles cboDatabase.BeforeDropDown
        Try
            If cboDatabase.Items.Count = 0 Then
                Cursor = Cursors.WaitCursor
                Dim oBL As New DatabaseManagement.BL.DatabaseManagement(cboSQLInstance.Text.Trim, "", "", True)
                Dim dt As New DataTable
                dt = oBL.LoadDatabaseList()
                With cboDatabase
                    .Items.Clear()
                    For Each oRow As DataRow In dt.Rows
                        .Items.Add(oRow("Name"))
                    Next
                End With

            End If
        Catch ex As Exception
            CommonFunction.ShowExclamation(ex.ToString)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub frmLogIn_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Try
            cboSQLInstance.Text = GetSetting(Application.ProductName, "ServerName", "ServerName")
            cbodatabase.Text = GetSetting(Application.ProductName, "DatabaseName", "DatabaseName")
            txtUserName.Text = GetSetting(Application.ProductName, "CurrentUser", "CurrentUser", "ADMIN")
        Catch ex As Exception
            CommonFunction.ShowExclamation(ex.ToString)
        End Try
    End Sub

#End Region
End Class